import urllib
import gdata
import gdata.service
import csv
import sys
import getopt
from gdata.service import RequestError


def rowToDict(s):
  c = s.split("\n")
  r = csv.reader(c)
  rows = []
  for row in r:
    rows.append(row)
  return rows

class FusionTables(gdata.service.GDataService):
  def __init__(self,email=None,password=None,source=None,server='tables.googlelabs.com',**kwargs):
    gdata.service.GDataService.__init__(self,email=email,password=password,service='fusiontables',source=source,server=server,**kwargs)

  def select(self,query):
    uri = "http://%s/api/query?sql=%s" % (self.server,urllib.quote(query.encode('utf-8')))
    return self.Get(uri,converter=rowToDict)

  def do(self, query, redirects_remaining=4, converter=None,extra_headers=None):
    uri = "http://%s/api/query" % self.server
    if extra_headers is None:
      extra_headers = {}
    if self._GDataService__gsessionid is not None:
      if uri.find('gsessionid=') < 0:
        if url_params is None:
          url_params = {}
        url_params['gsessionid'] = self.GDataService.__gsessionid

    http_data = 'sql=' + urllib.quote(query.encode('utf-8'))
    http_data = http_data.replace("%20","+")
    content_type = 'application/x-www-form-urlencoded'
    extra_headers['Content-Type'] = content_type
    server_response = self.request('POST', uri, data=http_data)
    result_body = server_response.read()

    if server_response.status == 201 or server_response.status == 200:
      if converter:
        return converter(result_body)
      else:
        return result_body

    elif server_response.status == 302:
      if redirects_remaining > 0:
        location = (server_response.getheader('Location')
                    or server_response.getheader('location'))
        if location is not None:
          m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
          if m is not None:
            self.__gsessionid = m.group(1) 
          return GDataService.PostOrPut(self, verb, data, location, 
              extra_headers, url_params, escape_params, 
              redirects_remaining - 1, media_source, converter=converter)
        else:
          raise RequestError, {'status': server_response.status,
              'reason': '302 received without Location header',
              'body': result_body}
      else:
        raise RequestError, {'status': server_response.status,
            'reason': 'Redirect received, but redirects_remaining <= 0',
            'body': result_body}
    else:
      raise RequestError, {'status': server_response.status,
          'reason': server_response.reason, 'body': result_body}
  def describe(self,id):
    uri = "http://%s/api/query?sql=DESCRIBE%%20%s" % (self.server,id)
    return self.Get(uri,converter=rowToDict)

def main(argv):
  username = ''
  password = ''
  try:
    opts, args = getopt.getopt(argv,"u:p:",[])
  except getopt.GetoptError:
    usage()
    sys.exit(2)
  for opt,arg in opts:
    if opt == "-u":
      username = arg
    elif opt == '-p':
      password = arg

  ft = FusionTables()
  ft.email = username
  ft.password = password
  ft.ProgrammaticLogin()

  r = ft.describe('139529')
  print r
  r = ft.do("CREATE TABLE test (rid: NUMBER);")
  print r
  r = ft.select("SELECT * FROM 139529")
  print r

if __name__ == "__main__":
  main(sys.argv[1:])
